﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace Common.Security.Cryptography
{
    public static class RandomNumberGeneratorEx
    {
        public static Int32 NextInt32(this RandomNumberGenerator rand)
        {
            Byte[] data = new Byte[sizeof(Int32)];
            rand.GetBytes(data);
            Int32 retVal = BitConverter.ToInt32(data, 0);
            if (retVal < 0)
            {
                retVal += Int32.MaxValue;
            }

            return retVal;
        }

        public static Double NextDouble(this RandomNumberGenerator rand)
        {
            Byte[] data = new Byte[sizeof(Int64)];
            rand.GetBytes(data);
            UInt64 retVal = BitConverter.ToUInt64(data, 0);
            return (Double)retVal / Int64.MaxValue;
        }

        public static Int32 NextInt32(this RandomNumberGenerator rand, Int32 min, Int32 max)
        {
            if (max <= min)
            {
                throw new ArgumentException("Max must be greater than Min.", "max");
            }
            else if (max == min + 1)
            {
                return min;
            }

            Int32 range = max - min;

            return min + (Int32)Math.Round(rand.NextDouble() * range);
        }
    }
}
